package com.sinping.qh.service.admin.statistics.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.domain.common.UnitDomain;
import com.sinping.qh.domain.lab.LabInspectItemTreeDomain;
import com.sinping.qh.domain.records.HiddendangerRecord;
import com.sinping.qh.dto.admin.statistics.HiddenDangerMainStaDTO;
import com.sinping.qh.dto.admin.statistics.HiddenDangerStaByYearDTO;
import com.sinping.qh.dto.admin.statistics.HiddenDangerStaMainByYearDTO;
import com.sinping.qh.dto.admin.statistics.HiddenDangerStatisticsDTO;
import com.sinping.qh.dto.common.CommonParamDTO;
import com.sinping.qh.dto.common.ICommonDTO;
import com.sinping.qh.repository.mongo.UnitRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemTreeRepository;
import com.sinping.qh.repository.mongo.records.HiddenDangerRecordRepository;
import com.sinping.qh.repository.mongo.records.impl.HiddenDangerRepositoryImpl;
import com.sinping.qh.service.admin.statistics.IStatisticsService;
import com.sinping.qh.service.app.records.IHiddenDangerService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.number.DecimalCalculate;
import com.sinping.qh.utils.time.ClockUtil;
import com.sinping.qh.utils.time.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author zhangjin
 * @create 2018/8/14
 */
@Service
public class StatisticsService implements IStatisticsService{


    @Autowired
    IHiddenDangerService iHiddenDangerService;

    @Autowired
    HiddenDangerRepositoryImpl hiddenDangerRepository;

    @Autowired
    UnitRepository unitRepository;

    @Autowired
    LabInspectItemTreeRepository labInspectItemTreeRepository;

    /**
     * 隐患统计
     * @return
     */
    @Override
    public String getHiddenDangerNumber(ICommonDTO iCommonDTO) {

        CommonParamDTO commonParamDTO =(CommonParamDTO)iCommonDTO;

        //查询检查项未删除隐患的总数量
        List<HiddendangerRecord> totalHidden= hiddenDangerRepository.findHiddenDangerCount(commonParamDTO,"check_item_one_id",
                Lists.newArrayList(),HiddendangerRecord.class,HiddendangerRecord.class
        );
        //查询检查项已删除隐患的总数量
        List<HiddendangerRecord> deleteHidden= hiddenDangerRepository.findInspectItemDeleteCount(commonParamDTO,
                HiddendangerRecord.class,HiddendangerRecord.class
        );


        long total=totalHidden.size()+deleteHidden.size();

        /**
         * 一、只查询院系的数,不查询校级的
         * 二、对于已经删除的数据,不查询,所以隐患分布的院系数中也要查询不删除的
         */
        List<UnitDomain> totalUnit= unitRepository.findAllByUnitTypeAndStatus(
                CommonDbConst.UNIT_TYPE_YUAN,
                CommonDbConst.DB_DELETE_NORMAL);

        //查询一级的隐患分布数
        ArrayList<String> checkItemOneList= Lists.newArrayList();
        checkItemOneList.add("check_item_one_id");
        checkItemOneList.add("check_item_one");
        List<HiddenDangerStatisticsDTO> hiddenDangerCheckOneList=
                hiddenDangerRepository.findHiddenDangerCount(commonParamDTO,"check_item_one_id",
                        checkItemOneList,HiddendangerRecord.class,HiddenDangerStatisticsDTO.class);

        for (HiddenDangerStatisticsDTO hiddenDangerStatisticsDTO:hiddenDangerCheckOneList ) {

            //需要把已经删除检查项的隐患归类为其它
            if(StringUtils.isBlank(hiddenDangerStatisticsDTO.getCheckItemOneId()))
            {
                hiddenDangerStatisticsDTO.setCheckCount(
                        (Long.parseLong(hiddenDangerStatisticsDTO.getCheckCount())+deleteHidden.size())+"");
            }

            Double num=(Double.parseDouble(hiddenDangerStatisticsDTO.getCheckCount())/total);
            String  scale =handleNum(num);

            hiddenDangerStatisticsDTO.setCheckScale(scale);
            //如果查询院系,则不需要进行院系统计
            if(StringUtils.isBlank(commonParamDTO.getUnitId())) {
                //查询院系的分布数量
                ArrayList<String> checkUnitOneList= Lists.newArrayList();
                checkUnitOneList.add("check_unit_id");
                List<HiddenDangerStatisticsDTO> hiddenDangerUnitOneList=
                        hiddenDangerRepository.findHiddenDangerUnitCount(commonParamDTO,"check_item_one_id"
                                ,hiddenDangerStatisticsDTO.getCheckItemOneId(),
                                checkUnitOneList,HiddendangerRecord.class,HiddenDangerStatisticsDTO.class);

                //需要把已经删除检查项的院系归类为其它
                if (StringUtils.isBlank(hiddenDangerStatisticsDTO.getCheckItemOneId())) {
                    List<HiddenDangerStatisticsDTO> hiddenDangerUnitDeleteList =
                            hiddenDangerRepository.findHiddenDangerDeleteUnitCount(commonParamDTO,
                                    checkUnitOneList, HiddendangerRecord.class, HiddenDangerStatisticsDTO.class);
                    hiddenDangerStatisticsDTO.setCheckUnitCount(hiddenDangerUnitDeleteList.size() + "");
                } else {
                    hiddenDangerStatisticsDTO.setCheckUnitCount(hiddenDangerUnitOneList.size() + "");
                }

                Double numUnit=(Double.parseDouble(hiddenDangerUnitOneList.size() + "") / Double.parseDouble(totalUnit.size() + ""));
                String  scaleUnit =handleNum(numUnit);

                hiddenDangerStatisticsDTO.setCheckUnitScale(scaleUnit);
            }
            LabInspectItemTreeDomain labInspectItemTreeDomain =
                     labInspectItemTreeRepository.findOne(hiddenDangerStatisticsDTO.getCheckItemOneId());
            //检查项被删除
            if (labInspectItemTreeDomain != null) {
                 hiddenDangerStatisticsDTO.setKind(labInspectItemTreeDomain.getItemSubcategory());

                 hiddenDangerStatisticsDTO.setHiddenType(labInspectItemTreeDomain.getItemCategory());
            }

        }

        //查询二级的隐患分布数
        ArrayList<String> checkItemTwoList= Lists.newArrayList();
        checkItemTwoList.add("check_item_one_id");
        checkItemTwoList.add("check_item_one");
        checkItemTwoList.add("check_item_two_id");
        checkItemTwoList.add("check_item_two");
        List<HiddenDangerStatisticsDTO> hiddenDangerCheckTwoList=
                hiddenDangerRepository.findHiddenDangerCount(commonParamDTO,"check_item_two_id",
                        checkItemTwoList,HiddendangerRecord.class,HiddenDangerStatisticsDTO.class);

        for (HiddenDangerStatisticsDTO hiddenDangerStatisticsDTO:hiddenDangerCheckTwoList ) {

            Double num=(Double.parseDouble(hiddenDangerStatisticsDTO.getCheckCount())/total);

            String  scale =handleNum(num);

            hiddenDangerStatisticsDTO.setCheckScale(scale);
            //如果查询院系,则不需要进行院系统计
            if(StringUtils.isBlank(commonParamDTO.getUnitId())) {
                //查询院系的分布数量
                ArrayList<String> checkUnitOneList = Lists.newArrayList();
                checkUnitOneList.add("check_unit_id");
                List<HiddenDangerStatisticsDTO> hiddenDangerUnitTwoList =
                        hiddenDangerRepository.findHiddenDangerUnitCount(commonParamDTO,"check_item_two_id"
                                , hiddenDangerStatisticsDTO.getCheckItemTwoId(),
                                checkUnitOneList, HiddendangerRecord.class, HiddenDangerStatisticsDTO.class);

                hiddenDangerStatisticsDTO.setCheckUnitCount(hiddenDangerUnitTwoList.size() + "");

                Double numUnit=(Double.parseDouble(hiddenDangerUnitTwoList.size() + "") /
                        Double.parseDouble(totalUnit.size() + ""));
                String  scaleUnit =handleNum(numUnit);

                hiddenDangerStatisticsDTO.setCheckUnitScale(scaleUnit);
            }

            LabInspectItemTreeDomain labInspectItemTreeDomain=
                    labInspectItemTreeRepository.findOne(hiddenDangerStatisticsDTO.getCheckItemOneId());

            //检查项被删除
            if(labInspectItemTreeDomain!=null) {
                hiddenDangerStatisticsDTO.setKind(labInspectItemTreeDomain.getItemSubcategory());

                hiddenDangerStatisticsDTO.setHiddenType(labInspectItemTreeDomain.getItemCategory());
            }
        }
        HiddenDangerMainStaDTO hiddenDangerMainStaDTO=new HiddenDangerMainStaDTO();

        hiddenDangerMainStaDTO.setCheckItemOne(hiddenDangerCheckOneList);

        hiddenDangerMainStaDTO.setCheckItemTwo(hiddenDangerCheckTwoList);


        return JsonMapper.defaultMapper().toJson(hiddenDangerMainStaDTO);
    }
    /**
     * 隐患按年统计
     * @return
     */
    @Override
    public String getHiddenDangerNumberByYear(ICommonDTO iCommonDTO) {

        CommonParamDTO commonParamDTO =(CommonParamDTO)iCommonDTO;

        List<HiddenDangerStaMainByYearDTO> hiddenDangerStaMainByYearDTOList =
                Lists.newArrayList();

        if(StringUtils.isNotBlank(((CommonParamDTO)iCommonDTO).getStartYear()) &&
                StringUtils.isNotBlank( ((CommonParamDTO) iCommonDTO).getEndYear())){
            String startYear= ((CommonParamDTO)iCommonDTO).getStartYear();
            String endYear= ((CommonParamDTO)iCommonDTO).getEndYear();

            Integer startYearByInt=Integer.parseInt(startYear);
            Integer endYearByInt=Integer.parseInt(endYear);

            for(int i=0;i<5;i++){


                commonParamDTO.setStartYear(String.valueOf(startYearByInt+i));
                commonParamDTO.setEndYear(String.valueOf(startYearByInt+i));
                HiddenDangerStaMainByYearDTO hiddenDangerStaMainByYearDTO=
                        getHiddenDangerStaMainByYearDTO(commonParamDTO);
                hiddenDangerStaMainByYearDTOList.add(hiddenDangerStaMainByYearDTO);
            }
        }
        else {
            Calendar calendar= Calendar.getInstance();
            int endYearByInt= calendar.get(Calendar.YEAR);
            Integer startYearByInt=endYearByInt-4;
            for(int i=0;i<5;i++){

                commonParamDTO.setStartYear(String.valueOf(startYearByInt+i));
                commonParamDTO.setEndYear(String.valueOf(startYearByInt+i));
                HiddenDangerStaMainByYearDTO hiddenDangerStaMainByYearDTO=
                        getHiddenDangerStaMainByYearDTO(commonParamDTO);
                hiddenDangerStaMainByYearDTOList.add(hiddenDangerStaMainByYearDTO);
            }
        }



        return JsonMapper.defaultMapper().toJson(hiddenDangerStaMainByYearDTOList);
    }

    private HiddenDangerStaMainByYearDTO getHiddenDangerStaMainByYearDTO(CommonParamDTO commonParamDTO)
    {
        //查询检查项未删除隐患的总数量
        List<HiddendangerRecord> totalHidden= hiddenDangerRepository.findHiddenDangerCount(commonParamDTO,"check_item_one_id",
                Lists.newArrayList(),HiddendangerRecord.class,HiddendangerRecord.class
        );
        //查询检查项已删除隐患的总数量
        List<HiddendangerRecord> deleteHidden= hiddenDangerRepository.findInspectItemDeleteCount(commonParamDTO,
                HiddendangerRecord.class,HiddendangerRecord.class
        );


        long total=totalHidden.size()+deleteHidden.size();
        //查询一级的隐患分布数
        ArrayList<String> checkItemOneList= Lists.newArrayList();
        checkItemOneList.add("check_item_one_id");
        checkItemOneList.add("check_item_one");
        List<HiddenDangerStaByYearDTO> hiddenDangerCheckOneList=
                hiddenDangerRepository.findHiddenDangerCount(commonParamDTO,"check_item_one_id",
                        checkItemOneList,HiddendangerRecord.class,HiddenDangerStaByYearDTO.class);

        List<HiddenDangerStaByYearDTO> hiddenDangerStaByYearDTOList=Lists.newArrayList();
        for (HiddenDangerStaByYearDTO hiddenDangerStaByYearDTO:hiddenDangerCheckOneList ) {

            //需要把已经删除检查项的隐患归类为其它
            if(StringUtils.isBlank(hiddenDangerStaByYearDTO.getCheckItemOneId()))
            {
                hiddenDangerStaByYearDTO.setCheckCount((Long.parseLong(hiddenDangerStaByYearDTO.getCheckCount())+deleteHidden.size())+"");
            }

            Double num=(Double.parseDouble(hiddenDangerStaByYearDTO.getCheckCount())/total);

            String scale=handleNum(num);

            hiddenDangerStaByYearDTO.setCheckScale(scale);

            //整改率
//            hiddenDangerRecordRepository.findAllByCheckItemOneIdAndHiddenDangerStatus
            List<HiddendangerRecord> hiddendangerRecordsByCheckItemId=
                    hiddenDangerRepository.findHiddenDangerByCheckItemIdAndHiddenDangerStatus(
                            commonParamDTO,hiddenDangerStaByYearDTO.getCheckItemOneId(),HiddendangerRecord.class,HiddendangerRecord.class
                    );
            String  scaleReadyRectify="";
            if(StringUtils.isBlank(hiddenDangerStaByYearDTO.getCheckItemOneId())){
                List<HiddendangerRecord> deleteHiddendangerRecordsByCheckItemId=
                        hiddenDangerRepository.findDelteHiddenDangerByCheckItemIdAndHiddenDangerStatus(
                                commonParamDTO,hiddenDangerStaByYearDTO.getCheckItemOneId(),HiddendangerRecord.class,HiddendangerRecord.class
                        );
                Double numScale=(Double.parseDouble(hiddendangerRecordsByCheckItemId.size()
                        +deleteHiddendangerRecordsByCheckItemId.size()
                        +"")/
                        Double.parseDouble(hiddenDangerStaByYearDTO.getCheckCount()));
                scaleReadyRectify = handleNum(numScale);

            }else {
                Double numScale=(Double.parseDouble(hiddendangerRecordsByCheckItemId.size() + "") /
                        Double.parseDouble(hiddenDangerStaByYearDTO.getCheckCount()));
                scaleReadyRectify=handleNum(numScale);
            }



            hiddenDangerStaByYearDTO.setCheckReadyRectify(scaleReadyRectify);

            LabInspectItemTreeDomain labInspectItemTreeDomain =
                    labInspectItemTreeRepository.findOne(hiddenDangerStaByYearDTO.getCheckItemOneId());
            //检查项被删除
            if (labInspectItemTreeDomain != null) {
                hiddenDangerStaByYearDTO.setHiddenType(labInspectItemTreeDomain.getItemCategory());
            }
            hiddenDangerStaByYearDTOList.add(hiddenDangerStaByYearDTO);
        }

        if(total>0) {
            //合计
            HiddenDangerStaByYearDTO hiddenDangerStaByYearDTO = new HiddenDangerStaByYearDTO();
            hiddenDangerStaByYearDTO.setCheckCount(String.valueOf(total));
            hiddenDangerStaByYearDTO.setHiddenType("合计");
            List<HiddendangerRecord> hiddendangerRecordsByCheckItemId =
                    hiddenDangerRepository.findAHiddenDangerByCheckItemIdAndHiddenDangerStatus(
                            commonParamDTO, null, HiddendangerRecord.class, HiddendangerRecord.class
                    );

            Double num=(Double.parseDouble(hiddendangerRecordsByCheckItemId.size() + "") /
                    Double.parseDouble(hiddenDangerStaByYearDTO.getCheckCount()));

            String scaleReadyRectify=handleNum(num);




            hiddenDangerStaByYearDTO.setCheckReadyRectify(scaleReadyRectify);
            hiddenDangerStaByYearDTOList.add(hiddenDangerStaByYearDTO);
        }

        HiddenDangerStaMainByYearDTO hiddenDangerStaMainByYearDTO =new HiddenDangerStaMainByYearDTO();

        hiddenDangerStaMainByYearDTO.setStaYear(commonParamDTO.getStartYear());

        hiddenDangerStaMainByYearDTO.setHiddenDangerStaByYearDTOList(hiddenDangerStaByYearDTOList);

        return hiddenDangerStaMainByYearDTO;
    }

    private String handleNum(Double num){
        return  DecimalCalculate.round((num)*100, 2)  + "";

    }

}
